/*
Copyright 2011 Masaki Muranaka

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
package org.monaka.radiation_levels;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import twitter4j.GeoLocation;
import twitter4j.StatusUpdate;
import twitter4j.Twitter;
import twitter4j.TwitterException;

import com.google.gdata.client.ClientLoginAccountType;
import com.google.gdata.client.GoogleService;
import com.google.gdata.client.Service.GDataRequest;
import com.google.gdata.client.Service.GDataRequest.RequestType;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ContentType;
import com.google.gdata.util.ServiceException;

public class PostServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -7129324942221712856L;
	private static final String APPLICATION_NAME = "org.monaka.radiation_levels";
	private static final String GOOGLE_ACCOUNT = ""; // TODO: you must fill in.
	private static final String PASSWORD = ""; // TODO: you must fill in.

	private static final String SERVICE_URL = "https://www.google.com/fusiontables/api/query";

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String comment = request.getParameter("comment");
		double lat;
		double lng;
		double uSv;
		try {
			String latS = request.getParameter("lat");
			lat = Double.parseDouble(latS);
			String lngS = request.getParameter("lng");
			lng = Double.parseDouble(lngS);
			String uSvS = request.getParameter("uSv");
			uSv = Double.parseDouble(uSvS);
		} catch (Exception e) {
			throw new ServletException(e);
		}

		String screenName = null;
		boolean isTweet = Boolean.parseBoolean(request.getParameter("tweet"));
		Twitter twitter = (Twitter) request.getSession()
				.getAttribute("twitter");
		String text = "計測地点の放射線量は" + uSv + "μSv/hでした．(" + comment + ")";

		try {
			if (isTweet) {
				StatusUpdate status = new StatusUpdate(text)
						.location(new GeoLocation(lat, lng));
				twitter.updateStatus(status);
			}
			screenName = twitter.getScreenName();
		} catch (TwitterException e) {
			throw new ServletException(e);
		}

		try {
			GoogleService service;
			service = new GoogleService("fusiontables", APPLICATION_NAME);
			service.setUserCredentials(GOOGLE_ACCOUNT, PASSWORD,
					ClientLoginAccountType.GOOGLE);
			String location = "<Point><coordinates>" + lng + "," + lat;
			String altS = request.getParameter("alt");
			if (altS != null & !("".equals(altS))) {
				location += "," + altS;
			}
			location += "</coordinates></Point>";
			SimpleDateFormat format = new SimpleDateFormat(
					"MM/dd/yy hh:mm:ss a");
			String sql = "INSERT INTO 924066 (uSv,comment,Date,Location,Acc,ReporterHash) values ("
					+ uSv
					+ ",'"
					+ comment
					+ "','"
					+ format.format(new Date())
					+ "','"
					+ location
					+ "',"
					+ request.getParameter("acc")
					+ ",'" + getHash(screenName) + "')";

			Logger logger = Logger.getLogger(this.getClass().getName());
			logger.warning(sql);

			URL url = new URL(SERVICE_URL);
			GDataRequest insertRequest = service
					.getRequestFactory()
					.getRequest(
							RequestType.INSERT,
							url,
							new ContentType("application/x-www-form-urlencoded"));
			OutputStreamWriter writer = new OutputStreamWriter(
					insertRequest.getRequestStream());
			writer.append("sql=" + URLEncoder.encode(sql, "UTF-8"));
			writer.flush();

			insertRequest.execute();
		} catch (AuthenticationException e) {
			throw new ServletException(e);
		} catch (ServiceException e) {
			throw new ServletException(e);
		} catch (NoSuchAlgorithmException e) {
			throw new ServletException(e);
		}

		response.sendRedirect(request.getContextPath() + "/");
	}

	private String getHash(String str) throws NoSuchAlgorithmException {
		MessageDigest md5 = MessageDigest.getInstance("MD5");
		md5.reset();
		md5.update((str + "radiation-salt").getBytes());
		byte[] hash = md5.digest();
		String strOut = "";
		for (int i = 0; i < hash.length; i++) {
			int d = hash[i];
			if (d < 0) {
				d += 256;
			}
			if (d < 16) {
				strOut += "0";
			}
			strOut += Integer.toString(d, 16);
		}
		return strOut;
	}
}